//
//  SEGSystemMessageViewController.m
//  ExcellentHome
//
//  Created by 揭婧雯 on 2016/12/9.
//  Copyright © 2016年 陈区. All rights reserved.
//

#import "SEGSystemMessageViewController.h"
#import "SEGWinningPublicViewController.h"

#import "SEGPropertyTableViewCell.h"

// 广告
#import "GDTUnifiedNativeAd.h"
#import "GDTUnifiedNativeAdView.h"
#import "UnifiedNativeAdMessageListCell.h"
#import <SEGPlatform/SEGAdDisplayManager.h>

#import "SEGSystemMessageViewModel.h"


@interface SEGSystemMessageViewController ()<UITableViewDelegate, UITableViewDataSource, GDTUnifiedNativeAdDelegate, GDTUnifiedNativeAdViewDelegate>

/** cell高度缓存(保证估算高度的准确性) */
@property (nonatomic, strong)NSMutableDictionary *cellHightDict;

/// 腾讯广告
@property (nonatomic, strong) NSArray<GDTUnifiedNativeAdDataObject *> *adDataArray;
@property (nonatomic, strong) GDTUnifiedNativeAd *unifiedNativeAd;
/// 表格
@property (nonatomic, strong) UITableView *tableView;

/// viewModel
@property (nonatomic, strong) SEGSystemMessageViewModel *viewModel;

@end

@implementation SEGSystemMessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    switch (self.type) {
        case SEGMessageVCType_System:
        {
            self.title = @"系统消息";
            break;
        }
        case SEGMessageVCType_Activity:
        {
            self.title = @"活动通知";
            break;
        }
        case SEGMessageVCType_Radio:
        {
            self.title = @"互助广播";
            break;
        }
        case SEGMessageVCType_HelpCheck:
        {
            self.title = @"审核通知";
            break;
        }
        case SEGMessageVCType_Recommend:
        {
            self.title = @"精选推荐";
            break;
        }
        case SEGMessageVCType_Mall:
        {
            self.title = @"应用通知";
            break;
        }
    }
    
    // 订阅信号
    @weakify(self);
    [[self.viewModel.command execute:self.groupId] subscribeNext:^(NSNumber *dataCount) {
        @strongify(self);
        if (dataCount.integerValue == 0) {
            [[SEGUhomeMediator sharedInstance] seg_showCustomProgressImage:@{@"view":self.tableView}];
        } else {
            [[SEGUhomeMediator sharedInstance] seg_hideCustomProgressImage:@{@"view":self.tableView}];
        }
        [self.tableView reloadData];
    }];
    
    //Load Tencent AD
    [self loadTencentAd];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView {
    return self.viewModel.dataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MessageModel* model = self.viewModel.dataArray[indexPath.section];
    if ([self hasTencentItem:model]) { // Tencent AD Cell
        NSString *tencentAdIdentifier = @"Tencent Cell";
        UnifiedNativeAdMessageListCell *cell = [tableView dequeueReusableCellWithIdentifier:tencentAdIdentifier];
        if (!cell) {
            cell = [[UnifiedNativeAdMessageListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tencentAdIdentifier];
            cell.backgroundColor = UIColor.clearColor;
        }
        [cell setupWithUnifiedNativeAdDataObject:self.adDataArray.firstObject delegate:self vc:self];
        return cell;
    }
    
    SEGPropertyTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"cellId"];
    if (cell == nil) {
        cell = [[SEGPropertyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellId"];
    }
    [cell cellWithModel:model];
    return cell;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    MessageModel *model = self.viewModel.dataArray[section];
    static NSString *headIdenty = @"headFootView";
    UITableViewHeaderFooterView *head = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headIdenty];
    if (!head) {
        head = [[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:headIdenty];
        
        UIView *timeView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), 44)];
        timeView.backgroundColor = kColor_bg;
        
        UILabel *dateLabel = [[UILabel alloc] init];
        dateLabel.textColor = kColor_3;
        dateLabel.font = [UIFont systemFontOfSize:13];
        dateLabel.tag = 100;
        
        [timeView addSubview:dateLabel];
        [dateLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(timeView).mas_offset(15);
            make.center.equalTo(timeView);
        }];
        [head addSubview:timeView];
    }
    
    UILabel *label = (UILabel *)[head viewWithTag:100];
    label.text = [SEGUtils getTimeStringInMessageDetailVCWithString:model.createTime];
    return head;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 44;
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellHeight_key = [NSString stringWithFormat:@"%ld_%ld",(long)indexPath.section, (long)indexPath.row];
    [self.cellHightDict setObject:@(cell.frame.size.height) forKey:cellHeight_key];
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = 67;
    NSString *cellHeight_key = [NSString stringWithFormat:@"%ld_%ld",(long)indexPath.section, (long)indexPath.row];
    height = [[self.cellHightDict objectForKey:cellHeight_key] floatValue];
    if (height == 0) height = 67;
    return height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    MessageModel* model = self.viewModel.dataArray[indexPath.section];
    if ([self hasTencentItem:model]) { // Tencent AD Cell
        return [UnifiedNativeAdMessageListCell cellHeightWithUnifiedNativeAdDataObject:self.adDataArray.firstObject];
    }
    return UITableViewAutomaticDimension;
}
- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    MessageModel *msgModel = self.viewModel.dataArray[indexPath.section];
    switch (self.type) {
        case SEGMessageVCType_System: //系统消息
        case SEGMessageVCType_Activity: //活动通知
            [[SEGUhomeMediator sharedInstance] seg_pushToViewControllerWithMessageType:@{@"model":msgModel, @"nav":self.navigationController}];
            break;
        case SEGMessageVCType_Radio: //求助广播
        {
            NSMutableDictionary *params = [@{@"objId" : msgModel.objectid,
                                             @"objType" : @"2",
                                             @"operationType" : [NSString stringWithFormat:@"%lu",(unsigned long)SEGNeighbourhoodOperationType_Help]
                                             } mutableCopy];
            UIViewController *vc = [[SEGUhomeMediator sharedInstance] seg_initNeihborhoodDetailViewController:params];
            [self.navigationController pushViewController:vc animated:YES];
            break;
        }
        case SEGMessageVCType_HelpCheck: //审核通知
        {
            NSMutableDictionary *params = [@{@"objId" : msgModel.objectid,
                                             @"objType" : @"2",
                                             @"operationType" : [NSString stringWithFormat:@"%lu",(unsigned long)SEGNeighbourhoodOperationType_Help]
                                             } mutableCopy];
            UIViewController *vc = [[SEGUhomeMediator sharedInstance] seg_initNeihborhoodDetailViewController:params];
            [self.navigationController pushViewController:vc animated:YES];
            break;
        }
        case SEGMessageVCType_Recommend: //精选推荐
        {
            NSDictionary *params = @{
                                     @"pictorialId":msgModel.objectid
                                     };
            UIViewController *vc = [[SEGUhomeMediator sharedInstance] seg_initPGCDeteailViewController:params];
            [self.navigationController pushViewController:vc animated:YES];
            break;
        }
        case SEGMessageVCType_Mall: //商场消息
        {
            [[SEGUhomeMediator sharedInstance] seg_pushToViewControllerWithMessageType:@{@"model":msgModel, @"nav":self.navigationController}];
            break;
        }
    }
}

#pragma mark - Tencent AD
- (BOOL)hasTencentItem:(MessageModel *)item {
    NSLog(@"%s %@",__FUNCTION__,item.messageId);
    
    // MessageModel 新增 tag 字段导致数据库操作失效，通过 messageId 来判断
    // BUG #31713 【4.9.10】IOS 物业通知栏有新消息，点击进入服务中心，展示缺省图 - APP
    if (!item.messageId) return YES;
    return NO;
}
- (void)insertDataSourceForTencentAd {
    if (self.viewModel.dataArray.count <= 0) return;
    // 精选推荐
    if (self.type == SEGMessageVCType_Recommend) {
        if ([[SEGAdDisplayManager shared] getAdWhetherShow:SEGAD_MessageRecommendType]) {
            [self segInsertData];
            return;
        }
    }
    // 活动通知
    if (self.type == SEGMessageVCType_Activity) {
        if ([[SEGAdDisplayManager shared] getAdWhetherShow:SEGAD_MessageActivityType]) {
            [self segInsertData];
            return;
        }
    }
}
- (void)segInsertData {
    // 插入腾讯广告占位数据
    NSMutableArray<MessageModel *> *temp = [NSMutableArray arrayWithArray:self.viewModel.dataArray];
    MessageModel *tencentAdItem = [[MessageModel alloc] init];
    tencentAdItem.createTime = self.viewModel.dataArray.firstObject.createTime;
    [temp insertObject:tencentAdItem atIndex:1];
    self.viewModel.dataArray = [NSArray arrayWithArray:temp];
}
- (void)loadTencentAd {
     self.unifiedNativeAd = [[GDTUnifiedNativeAd alloc] initWithPlacementId:kGDTPosIdMessageDetailList];
     self.unifiedNativeAd.delegate = self;
     [self.unifiedNativeAd loadAd];
}

#pragma mark - GDTUnifiedNativeAdDelegate
- (void)gdt_unifiedNativeAdLoaded:(NSArray<GDTUnifiedNativeAdDataObject *> * _Nullable)unifiedNativeAdDataObjects error:(NSError * _Nullable)error {
    NSLog(@"广告数据回调,%s",__FUNCTION__);
    if (!error && unifiedNativeAdDataObjects.count > 0) {
        NSLog(@"成功请求到广告数据:%zd",unifiedNativeAdDataObjects.count);
        self.adDataArray = unifiedNativeAdDataObjects;
        if (self.adDataArray && self.adDataArray.count > 0) {
            [self insertDataSourceForTencentAd];
            [self.tableView reloadData];
        }
        return;
    }
    NSLog(@"广告数据回调,%s,%@",__FUNCTION__,error.localizedDescription);
}

#pragma mark - Getter
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), LYScreenHeight() - kNavigationBarAndStatusBarHeight) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [UIView new];
        _tableView.sectionFooterHeight = 0;
        _tableView.backgroundColor = kColor_bg;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[SEGPropertyTableViewCell class] forCellReuseIdentifier:@"cellId"];
        [self.view addSubview:_tableView];
        //    self.tableView.rowHeight = 168;
        self.tableView.separatorColor = kColor_L2;
        self.tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0); //设置端距
    }
    return _tableView;
}
- (SEGSystemMessageViewModel *)viewModel {
    if (!_viewModel) _viewModel = [SEGSystemMessageViewModel new];
    return _viewModel;
}
- (NSMutableDictionary *)cellHightDict {
    if (!_cellHightDict) _cellHightDict = [NSMutableDictionary new];
    return _cellHightDict;
}

@end
